<!--
 * @Author: weidewei
 * @Date: 2025-11-01 09:54:37
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-01 10:43:55
 * @Description: 
 * @FilePath: \2025-front-face\review-knowledge\20251031\复习事件循环.html
-->
<script>
  // 题目1：基础优先级排序（同步→nextTick→微任务→宏任务）输出：start，end，nextTick，promise，timeout
  console.log("start");

  process.nextTick(() => console.log("nextTick"));
  Promise.resolve().then(() => console.log("promise"));
  setTimeout(() => console.log("timeout"), 0);

  console.log("end");

  //   题目2：async/await的微任务包装​ 输出：start，foo start，end，foo end，promise，timeout
  console.log("start");

  async function foo() {
    console.log("foo start");
    await Promise.resolve(); // 等价于 Promise.then(...)
    console.log("foo end");
  }

  foo();
  setTimeout(() => console.log("timeout"), 0);
  Promise.resolve().then(() => console.log("promise"));

  console.log("end");

  //   题目3：setImmediatevs setTimeout的阶段顺序​ 输出：start，end，nextTick，setImmediate，setTimeout
  console.log("start");

  setTimeout(() => console.log("timeout"), 0); // timers 阶段
  setImmediate(() => console.log("immediate")); // check 阶段
  process.nextTick(() => console.log("nextTick")); // nextTick 优先级最高

  console.log("end");

  //   题目4：I/O 回调中的微任务与 setImmediate 输出：start，end,nextTick,fs callback,promise in io,immediate in io,timeout
  const fs = require("fs");

  console.log("start");

  fs.readFile(__filename, () => {
    // I/O 回调（poll 阶段）
    console.log("fs callback");
    Promise.resolve().then(() => console.log("promise in io")); // 微任务
    setImmediate(() => console.log("immediate in io")); // check 阶段
  });

  setTimeout(() => console.log("timeout"), 0); // timers 阶段
  process.nextTick(() => console.log("nextTick")); // nextTick

  console.log("end");

  //   题目5：嵌套的宏任务与微任务​ 输出：start，end,promise2,timeout1,promise1,timeout2
  console.log("start");

  setTimeout(() => {
    console.log("timeout1");
    Promise.resolve().then(() => console.log("promise1")); // 宏任务中的微任务
  }, 0);

  Promise.resolve().then(() => {
    console.log("promise2");
    setTimeout(() => console.log("timeout2")); // 微任务中的宏任务
  });

  console.log("end");
</script>
